<template>
  <div>
    <span class='title'>用户管理</span>
    <div class='card'>
      <el-card :style="{ height: '1150px' }">
        <div>
          <el-input v-model='input' placeholder='请输入姓名或者ID' style='width: 200px;height: 100px'></el-input>
          <el-select v-model="value" placeholder="请选择用户类型" style="width: 200px;height: 80px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <span class='button-container'>
            <el-button type='primary1' @click="select"><i class="el-icon-search"></i> 查询</el-button>
            <el-button type='primary2' @click="fetchData"><i class="el-icon-refresh"></i> 重置</el-button>
            <el-button class='new-user-button' type='primary' @click='openNewUserDialog'><i class="el-icon-plus"></i> 新建用户</el-button>
          </span>
        </div>
        <div>
          <el-row :gutter='20'>
            <el-col v-for='user in paginatedUsers' :key='user.uid' :span='8'>
              <el-card>
                <div class='user-info'>
                  <p>
                    <el-icon class="icon-blue" name="user-solid"></el-icon>
                    <strong>姓名:</strong> {{ user.name }}
                  </p>
                  <p>
                    <el-icon class="icon-blue" name="document"></el-icon>
                    <strong>ID:</strong> {{ user.uid }}
                  </p>
                  <p>
                    <el-icon class="icon-blue" name="document"></el-icon>
                    <strong>Token:</strong> {{ user.token }}
                  </p>
                  <p>
                    <el-icon class="icon-blue" name="star-on"></el-icon>
                    <strong>用户类型:</strong>
                    <span :class="'type-' + user.type.toLowerCase()" class='user-type'>{{ user.type }}</span>
                  </p>
                </div>
                <div class='card-actions'>
                  <el-button class='edit-button' @click='openEditDialog(user)'><i class="el-icon-edit"></i> 编辑
                  </el-button>
                  <el-button class='delete-button' @click='confirmDelete(user)'><i class="el-icon-delete"></i> 删除
                  </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>
          <div class='pagination-container'>
            <el-pagination
                :current-page='currentPage'
                :page-size='pageSize'
                :page-sizes="[3, 6, 9]"
                :total='users.length'
                background
                layout='sizes, prev, pager, next, jumper'
                @current-change='handlePageChange'
                @size-change='handleSizeChange'
            ></el-pagination>
          </div>

          <!-- 新建用户弹窗 -->
          <el-dialog :visible.sync='newUserDialogVisible' title='新建用户'>
            <el-form ref='newUserForm' :model='newUser' :rules='newUserRules'>
              <el-form-item label='姓名' prop='name'>
                <el-input v-model='newUser.name'></el-input>
              </el-form-item>
              <el-form-item label='用户类型' prop='type'>
                <el-select v-model='newUser.type' placeholder='请选择用户类型'>
                  <el-option v-for='item in options' :key='item.value' :label='item.label'
                             :value='item.label'></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label='注册令牌' prop='token'>
                <el-input v-model='newUser.token'></el-input>
              </el-form-item>
            </el-form>
            <div slot='footer' class='dialog-footer'>
              <el-button @click='newUserDialogVisible = false'>取消</el-button>
              <el-button type='primary' @click='saveNewUser'>保存</el-button>
            </div>
          </el-dialog>

          <!-- 显示新建用户信息的确认弹窗 -->
          <el-dialog :visible.sync='showUserInfoDialog' title='确认新建用户信息'>
            <p><strong>姓名:</strong> {{ newUser.name }}</p>
            <p><strong>用户类型:</strong> {{ newUser.type }}</p>
            <p><strong>注册令牌:</strong> {{ newUser.token }}</p>
            <div slot='footer' class='dialog-footer'>
              <el-button @click='newUserDialogVisible = false'>取消</el-button>
              <el-button @click='createNewUser'>确认</el-button>
            </div>
          </el-dialog>

          <!-- 编辑用户弹窗 -->
          <el-dialog :visible.sync='editDialogVisible' title='编辑用户信息'>
            <el-form :model='currentUser'>
              <el-form-item label='姓名'>
                <el-input v-model='currentUser.name'></el-input>
              </el-form-item>
              <el-form-item label='用户类型'>
                <el-select v-model='currentUser.type' placeholder='请选择用户类型'>
                  <el-option v-for='item in options' :key='item.value' :label='item.label'
                             :value='item.label'></el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div slot='footer' class='dialog-footer'>
              <el-button @click='editDialogVisible = false'>取消</el-button>
              <el-button type='primary' @click='updateUser'>保存</el-button>
            </div>
          </el-dialog>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import {selectAdm, deleteAdm, updateAdm, createAdm, getAllAdm} from '../../../../api/api'

export default {
  data () {
    return {
      input: '',
      options: [
        {value: '选项1', label: '辅导员'},
        {value: '选项2', label: '院系辅导员'}
      ],
      value: '',
      users: [],
      currentPage: 1,
      pageSize: 9,
      editDialogVisible: false,
      currentUser: {},
      newUserDialogVisible: false,
      newUser: {
        name: '',
        uid: '',
        type: '',
        token: ''
      },
      showUserInfoDialog: false, // 控制显示新建用户信息的确认弹窗
      newUserRules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        type: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
        token: [{ required: true, message: '请输入注册令牌', trigger: 'blur' }]
      }
    }
  },
  computed: {
    paginatedUsers () {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.users.slice(start, end)
    }
  },
  async created () {
    await this.fetchData()
  },
  methods: {
    async fetchData () {
      try {
        const res = await getAllAdm()
        if (res.status && res.data) {
          this.users = res.data.filter(item => item.isEnabled && !item.isDeleted)
            .map(item => ({
              name: item.loginName,
              uid: item.id,
              type: this.mapPermissionLevel(item.permissionLevel),
              token: item.token
            }))
        } else {
          console.error('获取数据失败:', res.message)
        }
      } catch (error) {
        console.error('获取数据错误:', error)
      }
    },
    async select () {
      try {
        if (!this.value) {
          this.$message.error('请选择一个用户类型')
          return
        }
        const json = {
          loginName: this.input,
          permissionLevel: this.mapPermissionLevel3(this.value)
        }
        console.log(json)
        const res = await selectAdm(json)
        if (res.status && res.data) {
          this.users = res.data.filter(item => item.isEnabled && !item.isDeleted)
            .map(item => ({
              name: item.loginName,
              uid: item.id,
              type: this.mapPermissionLevel(item.permissionLevel),
              token: item.token
            }))
        } else {
          console.error('获取数据失败:', res.message)
        }
      } catch (error) {
        console.error('获取数据错误:', error)
      }
    },
    mapPermissionLevel (level) {
      // 根据后端返回的权限级别映射到对应的用户类型
      switch (level) {
        case 1:
          return '超级管理员'
        case 2:
          return '院系辅导员'
        case 3:
          return '辅导员'
        default:
          return '未知类型'
      }
    },
    mapPermissionLevel2 (level) {
      // 根据权限级别映射到对应的数字
      switch (level) {
        case '超级管理员':
          return 1
        case '院系辅导员':
          return 2
        case '辅导员':
          return 3
        default:
          return 0
      }
    },
    mapPermissionLevel3 (level) {
      // 根据权限级别映射到对应的数字
      switch (level) {
        case '选项1':
          return 3
        case '选项2':
          return 2
        case '选项3':
          return 1
        default:
          return 0
      }
    },
    handlePageChange (page) {
      this.currentPage = page
    },
    handleSizeChange (size) {
      this.pageSize = size
    },
    openEditDialog (user) {
      // 使用深拷贝避免直接修改原始数据
      this.currentUser = {...user}
      this.editDialogVisible = true
    },
    async updateUser () { // 创建用户
      try {
        let json = {
          id: this.currentUser.uid,
          loginName: this.currentUser.name,
          permissionLevel: this.mapPermissionLevel2(this.currentUser.type)
        }
        await updateAdm(json) // 等待更新操作完成
        this.editDialogVisible = false
        await this.fetchData() // 等待数据刷新操作完成
      } catch (error) {
        console.error('Error creating admin:', error)
      }
    },
    confirmDelete (user) {
      this.$confirm(`你确定要删除用户 ${user.name} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteUser(user)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async deleteUser (user) {
      try {
        let json = {
          id: user.uid
        }
        await deleteAdm(json) // 等待更新操作完成
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        await this.fetchData() // 等待数据刷新操作完成
      } catch (error) {
        console.error('Error creating admin:', error)
      }
    },
    openNewUserDialog () {
      // 打开新建用户弹窗时清空输入框内容
      this.newUserDialogVisible = true
      this.newUser = {
        name: '',
        uid: '',
        type: '',
        token: ''
      }
    },
    async saveNewUser () { // 创建用户时的辅助方法
      this.$refs.newUserForm.validate((valid) => {
        if (valid) {
          // 执行保存新用户的操作
          console.log('保存新用户:', this.newUser)
          this.newUserDialogVisible = false
          // 显示新建用户信息的确认弹窗
          this.showUserInfoDialog = true
        } else {
          console.log('请完整填写表单')
          return false
        }
      })
    },
    async createNewUser () { // 创建用户
      try {
        let newAdmin = {
          loginName: this.newUser.name,
          token: this.newUser.token,
          permissionLevel: this.mapPermissionLevel2(this.newUser.type)
        }
        await createAdm(newAdmin)
        // 重置新管理员数据
        this.newUser = {
          name: '',
          email: '',
          role: ''
        }
        this.newUserDialogVisible = false
        // 显示新建用户信息的确认弹窗
        this.showUserInfoDialog = false
        await this.fetchData()
      } catch (error) {
        console.error('Error creating admin:', error)
      }
    }
  }
}
</script>

<style scoped>
.title {
  width: 250px;
  height: 28px;
  opacity: 1;
  color: #000000e6;
  text-align: left;
  font-size: 20px;
  font-weight: 500;
  line-height: 28px;
  padding: 20px;
  display: block;
}

.card {
  margin-left: 20px;
  margin-right: 20px;
}

.el-button--primary1 {
  background-color: #166aff;
  border-color: #166aff;
  color: white;
}

.el-button--primary2 {
  background-color: white;
  border-color: #166aff;
  color: #166aff;
}

.button-container {
  margin-left: 50px;
}

.user-info {
  padding: 20px;
}

.card-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.card-actions .el-button {
  flex: 1;
  margin: 0 5px;
}

.edit-button {
  background-color: #166aff;
  border-color: #166aff;
  color: white;
}

.delete-button {
  background-color: white;
  border-color: #166aff;
  color: #166aff;
}

.pagination-container {
  margin-top: 20px;
  height: 100px;
  position: absolute;
  left: 720px;
}

.el-pagination .el-pager .active {
  background-color: #409eff;
  color: white;
}

.el-pagination .el-pager li:hover {
  background-color: #409eff;
  color: white;
}

.dialog-footer {
  text-align: right;
}

.user-type {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 5px;
  border: 2px solid;
  font-weight: bold;
  text-align: center;
  margin-top: 5px;
}

.type-学校用户 {
  border-color: #409eff;
  background-color: #e6f7ff; /* 背景色 */
}

.type-辅导员 {
  border-color: #67c23a;
  background-color: #f0f9eb; /* 背景色 */
}

.type-院系辅导员 {
  border-color: #e6a23c;
  background-color: #fffbe6; /* 背景色 */
}

.type-院系管理员 {
  border-color: #00fba3;
  background-color: #fffbe6; /* 背景色 */
}

.type-超级管理员 {
  border-color: #f56c6c;
  background-color: #ffe2e2; /* 背景色 */
}

.icon-blue {
  color: #166aff;
}

.new-user-button {
  background-color: #166aff;
  border-color: #166aff;
  color: white;
}
</style>
